package com.ruben.simplescaffold.handler;

import cn.dev33.satoken.exception.NotLoginException;
import cn.hutool.core.exceptions.ValidateException;
import cn.hutool.core.util.StrUtil;
import com.ruben.simplescaffold.exception.PageException;
import com.ruben.simplescaffold.exception.ParamException;
import com.ruben.simplescaffold.exception.ServerException;
import com.ruben.simplescaffold.exception.UserNotFoundException;
import com.ruben.simplescaffold.pojo.common.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.io.IOException;

/**
 * 全局异常处理
 *
 * @author <achao1441470436@gmail.com>
 * @since 2021/5/21 0021 21:08
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    public static final String QUOTES = "'";

    @ExceptionHandler(Throwable.class)
    public void throwableHandler(Throwable e) {
        log.error("unknown error", e);
    }

    @ExceptionHandler(PageException.class)
    public void pageExceptionHandler(PageException e) throws IOException {
        log.error("page error：" + e.getMessage());
//        response.sendRedirect("/");
    }

    @ExceptionHandler(ParamException.class)
    public Result paramExceptionHandler(ParamException e) {
        if (log.isErrorEnabled()) {
            log.warn("param error", e);
        }
        return Result.paramError().msg(e.getMsg());
    }

    @ExceptionHandler(ServerException.class)
    public Result serverExceptionHandler(ServerException e) {
        log.error("server error", e);
        return Result.paramError().msg(e.getMsg());
    }

    @ExceptionHandler(UserNotFoundException.class)
    public Result accountNotFoundException(UserNotFoundException e) {
        if (log.isInfoEnabled()) {
            log.error("UserNotFoundException,maybe not login", e);
        }
        return Result.notLogin().msg(e.getMsg());
    }

    @ExceptionHandler(ValidateException.class)
    public Result validateException(ValidateException e) {
        if (log.isInfoEnabled()) {
            log.error("param error", e);
        }
        return Result.paramError().msg(e.getMessage());
    }

    @ExceptionHandler(DuplicateKeyException.class)
    public Result duplicateKeyException(DuplicateKeyException e) {
        if (log.isInfoEnabled()) {
            log.error("param error", e);
        }
        return Result.paramError().msg(StrUtil.subBetween(e.getMessage(), QUOTES) + " 重复");
    }

    @ExceptionHandler(NotLoginException.class)
    public Result accountNotFoundException(NotLoginException e) {
        if (log.isInfoEnabled()) {
            log.error("param error", e);
        }
        return Result.notLogin().msg(e.getMessage());
    }

}
